import ArticleItem from "@/components/ArticleItem";
import { getArticleList } from "@/store/actions/home";
import { RootState } from "@/types/store";
import { InfiniteScroll, PullToRefresh } from "antd-mobile";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import styles from "./index.module.scss";
type Props = {
    channelId: number;
};
const ArticleList = ({ channelId }: Props) => {
    const dispatch = useDispatch();
    // 获得文章列表
    const { channelArticles } = useSelector((state: RootState) => state.home);

    // 默认文章
    const curChannelArticles = channelArticles[channelId] ?? {
        pre_timestamp: +new Date() + "",
        results: [],
    };
    const { pre_timestamp, results } = curChannelArticles;
    // 无限加载
    const loadMore = async () => {
        await dispatch(getArticleList(channelId, pre_timestamp));
    };
    // 下拉刷新文章列表
    const onRefresh = async () => {
        await dispatch(getArticleList(channelId, Date.now() + ""));
    };
    const hasMore = pre_timestamp !== null;
    const history = useHistory();
    return (
        <div className={styles.root}>
            <PullToRefresh onRefresh={onRefresh}>
                {/* 文章列表中的每一项 */}
                {results.map((item, index) => {
                    const {
                        art_id,
                        title,
                        aut_name,
                        comm_count,
                        pubdate,
                        cover: { type, images },
                    } = item;
                    const articleData = {
                        title,
                        aut_name,
                        comm_count,
                        pubdate,
                        type,
                        images,
                    };

                    return (
                        <div
                            key={index}
                            className="article-item"
                            onClick={() => history.push(`/article/${art_id}`)}>
                            <ArticleItem {...articleData} />
                        </div>
                    );
                })}
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
        </div>
    );
};

export default ArticleList;
